package com.coincalf.task.event;

import com.coincalf.dto.MarketDTO;
import com.coincalf.dto.TurnoverDataDTO;
import com.coincalf.feign.MarketServiceClient;
import com.coincalf.feign.TradeTurnoverOrderServiceClient;
import com.coincalf.framework.enums.KlineType;
import com.coincalf.task.service.TradeKLineService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.List;

/**
 * @author qiang
 */
@Component
@Slf4j
public class TradeKLineEvent implements IEvent {

    @Autowired
    private TradeTurnoverOrderServiceClient tradeTurnoverOrderServiceClient;
    @Autowired
    private TradeKLineService tradeKLineService;
    @Autowired
    private MarketServiceClient marketServiceClient;

    @Override
    public void handle() {
        //获取所有有效的币币交易对
        List<MarketDTO> markets = marketServiceClient.tradeMarkets();
        if (!CollectionUtils.isEmpty(markets)) {
            for (MarketDTO market : markets) {
                //根据交易对id查询3秒到现在的状态有效的币币交易成交数据
                TurnoverDataDTO turnoverData = tradeTurnoverOrderServiceClient.turnoverData(market.getId());
                // 格式化价格小数位数与交易对价格小数位数保持一致
                turnoverData.setPrice(turnoverData.getPrice().setScale(market.getPriceScale(), BigDecimal.ROUND_HALF_UP));
                turnoverData.setVolume(turnoverData.getVolume().setScale(market.getNumScale(), BigDecimal.ROUND_HALF_UP));
                for (KlineType klineType : KlineType.values()) {
                    tradeKLineService.generateKLine(market.getSymbol(), turnoverData.getPrice(), turnoverData.getVolume(), market.getOpenPrice(), klineType);
                }
            }
        }
    }

}
